# -*- coding:utf-8 -*- #

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor, defer
from twisted.internet.endpoints import TCP4ServerEndpoint

from logger.logger import getlogger
from db.jsondata import jsonloads
from configure import logger_path
from db.fastdb import FastDb

class GSProtocol(Protocol):
    def __init__(self):
        self.length = 0
        self.total = ''
        self.content = ''
        pass

    def parse_data(self, data):
        '''
        分析接收的数据，过滤出$符左的长度，右的内容
        '''
        self.total = '%s%s' % (self.total, data)
        if not self.length and '$' in self.total:
            index = self.total.index('$')
            self.length = int(self.total[0:index])
            # 获取$右边的数据
            self.content = self.total[index+1: index+self.length + 1]

        # 判断数据完整性
        if int(self.length) == len(self.content) and self.length > 0:
            self.total = self.total[index+1+self.length:]
            self.length = 0
            return True
        return False
    
    def connectionMade(self):
        #print '客户端连接 ' , self.transport.client
        pass

    def dataReceived(self, data):
        
        '''
        接收数据格式
        176 是数据长度
        176${"filter": "monitor_filter", 
             "内存使用": [3920, "MB"], 
             "datetime": 1333695036, 
             "内存剩余":[175, "MB"], 
             "type": 3, 
             "id": 180, 
             "is_attention": 1} 1表示是报警数据 0 表示正常
        '''
        #print self.transport.client
        print "接收数据为: " ,data
        if not self.parse_data(data):
            return

        d = defer.Deferred()
        d.addCallback(self.process)
        data = self.content
        reactor.callLater(0, d.callback, data)
        self.content = ''

    def process(self, data):
        '''
        数据处理操作

        data = {"filter": "monitor_filter", 
             "内存使用": [3920, "MB"], 
             "datetime": 1333695036, 
             "内存剩余":[175, "MB"], 
             "type": 3, 
             "id": 180, 
             "is_attention": 1} 
        '''

        try:
            # data 是字符串
            data = jsonloads(data)
            
            #转换后的data是字典 或 叫json数据格式
        except ValueError:
            self.transport.write('{"error_msg": "json format error"}')
            getlogger(logger_path).error('json format error')
            return
        #self.transport.write('test')
        #print "data数据:",data
        try:
            # pop 将type的value给dtype，并删除字典中的type和它对应的值
            dtype = str(data.pop('type'))
            
        except KeyError:
            return

        '''
        删除type后的数据

        data = {"filter": "monitor_filter", 
             "内存使用": [3920, "MB"], 
             "datetime": 1333695036, 
             "内存剩余":[175, "MB"], 
             "id": 180, 
             "is_attention": 1} 
             
        3 monitor数据
        4 probe重载配置文件
        '''
        if dtype == '1':
            self.query(data)
        elif dtype == '2':
            self.propelling(data)
        elif dtype == '3':
            self.commit(data)
        elif dtype == '4':
            self.reset_alarm(data)
        else:
            return


    def reset_alarm(self, data):
        print 'reset_alarm', data
        ids = data.pop('ids')
        if not ids:
            #ids为空,即不知道监控项id号
            pass
        else:
            fastdb = FastDb()
            [fastdb.delete2alarm(item_id) for item_id in ids]

    def connectionLost(self, reason):
        pass
    
    def propelling(self, data):
        from propeller import alarm_propelling
        alarm_propelling.propelling(self.transport)
        
    def commit(self, data):
        '''
        将数据保存到数据库中
        '''
        try:
            #删除字典标志，并得到标志的内容
            datatype = data.pop('filter')
        except KeyError:
            getlogger(logger_path).error('has not key:%s' % KeyError.message)
            return

        fastdb = FastDb()

        print "保存数据库的数据时 data",data
        
        '''
        删除filter后的数据

        data = {"内存使用": [3920, "MB"], 
             "datetime": 1333695036, 
             "内存剩余":[175, "MB"], 
             "id": 180, 
             "is_attention": 1} 
             
        '''
        if datatype == 'monitor_filter':
            fastdb.save2monitor(data)
        elif datatype == 'alarm_filter':
            fastdb.save2alarm(data)
        elif datatype == 'logger_filter':
            fastdb.save2logger(data)

    def query(self, data):
        fastdb = FastDb()
        fastdb.query(self.transport, data)

def initial():
    #TODO:initial alarm data from redis

    factory = Factory()
    factory.protocol = GSProtocol
    endpoint = TCP4ServerEndpoint(reactor, 2000)
    endpoint.listen(factory)
    reactor.run()

if __name__ == '__main__':
    initial()
